import React from 'react';
import { Row, Col, Form, InputNumber, Input, Button, Table, Select, message } from 'antd';
const R = require('ramda');
import BizParams from '../../../components/commons/BizParams';
import ChooseProduct from '../components/ChooseProduct';
import validator from '../../../utils/Validator'
import Constants from '../../../utils/Constants'
const pricePercent = 0.1;

const FormItem = Form.Item;
export default Form.create({ wrappedComponentRef: true })(class ProductInfo extends React.Component {
    constructor(props) {
        super(props);
        this.initData(props.dataSource, true);
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.dataSource)(nextProps.dataSource)) {
            this.initData(nextProps.dataSource)
        }
    }

    initData = (dataSource, flag) => {
        dataSource = R.isNil(dataSource) ? {} : dataSource;
        let defaultProductList = R.isNil(dataSource.orderProducts) ? [] : dataSource.orderProducts;
        let defaultPacktypeelse = dataSource.kindpackage && dataSource.kindpackage.split('|').includes('99');
        let defaultRetrodictRate = dataSource.drawertype === "2";
        if (flag) {
            this.state = {
                retrodictFlag: false,   //倒推增加一个刷新价格按钮，避免过多事件的监听，点下一步之前必须保证为false
                packtypeelse: defaultPacktypeelse,
                defaultPacktypeelse: defaultPacktypeelse,
                productList: defaultProductList,
                defaultProductList: defaultProductList,
                defaultRetrodictRate: defaultRetrodictRate,
                retrodictRate: defaultRetrodictRate //true：倒推 false: 正推
            }
        } else {
            this.setState({
                retrodictFlag: false,   //倒推增加一个刷新价格按钮，避免过多事件的监听，点下一步之前必须保证为false
                packtypeelse: defaultPacktypeelse,
                defaultPacktypeelse: defaultPacktypeelse,
                productList: defaultProductList,
                defaultProductList: defaultProductList,
                defaultRetrodictRate: defaultRetrodictRate,
                retrodictRate: defaultRetrodictRate
            })
        }
    }

    form = {};

    handleCollectForm = () => {
        return this.form;
    }

    handleResetFields = () => {
        this.setState({ packtypeelse: this.state.defaultPacktypeelse, productList: this.state.defaultProductList, retrodictRate: this.state.defaultRetrodictRate, retrodictFlag: false });
        this.props.form.resetFields();
    }

    handleChangeKindPackage = (value) => {
        if (value && value.includes('99')) {
            this.setState({ packtypeelse: true });
        } else {
            this.setState({ packtypeelse: false, packtypeelse: "" });
        }
    }

    checkProductInfo = () => {
        let flag = true
        let currency = ""
        if (this.props.handleGetCurrencyType) {
            currency = this.props.handleGetCurrencyType();
        }
        let productDrawerIds = [];
        this.props.form.validateFields((errors, values) => {
            if (errors) {
                if (!this.state.packtypeelse) errors = R.omit(['packtypeelse'])(errors);//实际种类
                if (R.isEmpty(errors)) errors = null;
            }
            if (errors) {
                flag = false;
            }
        })

        if (R.isEmpty(this.state.productList)) {
            message.error("请至少选择一个产品!");
            flag = false;
        }

        let totalpacknum = 0;
        R.map((row) => {
            if (row.currency !== currency) {
                message.error("所选产品币种必须与报关币种保持一致，请重新选择!");
                flag = false;
                return;
            }
            if (R.isNil(row.number) || R.isNil(row.packageNumber) || R.isNil(row.netWeight) || R.isNil(row.grossWeight) || R.isNil(row.price)
                || (this.state.retrodictRate && (R.isNil(row.retrodictcost) || R.isNil(row.draweramount)))) {
                message.error("产品：(" + row.name + ") 信息不全，除规格外其他为必填项，请补全!");
                flag = false;
                return;
            }


            if (!(validator.DECIMAL4.pattern.test(row.number) && validator.DECIMAL4.pattern.test(row.netWeight) && validator.DECIMAL4.pattern.test(row.grossWeight))
                || (this.state.retrodictRate && !validator.DECIMAL4.pattern.test(row.draweramount))) {
                if (this.state.retrodictRate) message.error("产品：(" + row.name + ") 信息有误，数量、净重、毛重、倒推开票金额都必须大于0且最多保留四位小数");
                else message.error("产品：(" + row.name + ") 信息有误，数量、净重、毛重都必须大于0且最多保留四位小数");
                flag = false;
                return;
            }
            if (row.grossWeight < row.netWeight) {
                message.error("产品：(" + row.name + ") 毛重不能小于净重");
                flag = false;
                return;
            }

            totalpacknum = totalpacknum + (R.isNil(row.packageNumber) ? 0 : row.packageNumber) //总包装件数
            productDrawerIds.push(row.drawerid + "");
        }, this.state.productList)

        if (flag) {
            this.form = R.merge(this.form, this.props.form.getFieldsValue());
            this.form.orderProducts = this.state.productList;
        }
        return flag
    };

    handleChangeProductNumber = (record, value) => {
        let productList = R.clone(this.state.productList);
        let customer = R.isNil(this.props.customer) ? {} : this.props.customer;
        let agencyfee = R.isNil(customer.agencyfee) ? 0 : customer.agencyfee / 100;//费率
        let retrodictRate = R.isNil(this.props.form.getFieldValue('retrodictrate')) ? 0 : this.props.form.getFieldValue('retrodictrate');
        R.map((row) => {
            if (row.id === record.id) {
                row.number = value;
                row.netWeight = Math.round(value * row.singleWeight * 10000) / 10000;
                if (this.state.retrodictRate && retrodictRate !== agencyfee) { //倒推 数量联动单价
                    let draweramount = R.isNil(row.draweramount) || R.isEmpty(row.draweramount) ? 0 : row.draweramount; //倒推开票金额默认为0
                    let retrodictcost = R.isNil(row.retrodictcost) || R.isEmpty(row.retrodictcost) ? 0 : row.retrodictcost; //倒推费用默认为0
                    let number = R.isNil(row.number) || R.isEmpty(row.number) ? 1 : row.number; //数量默认为1
                    row.price = ((draweramount * (1 + row.zzrate / 100 - row.taxrate / 100) / (1 + row.zzrate / 100) + retrodictcost) / (retrodictRate - agencyfee) / number).toFixed(4);
                }
                row.totalPrice = Math.round(row.price * row.number * 100) / 100;

            }
        }, productList)
        this.setState({ productList: productList });
    }

    handleChangePackageNumber = (record, value) => {
        let productList = R.clone(this.state.productList);
        R.map((row) => {
            if (row.id === record.id) {
                row.packageNumber = value;
            }
        }, productList)
        this.setState({ productList: productList });
    }

    handleChangeProductPrice = (record, value) => {
        let productList = R.clone(this.state.productList);
        R.map((row) => {
            if (row.id === record.id) {
                row.price = value;
                row.totalPrice = Math.round(value * row.number * 100) / 100;
            }
        }, productList)
        this.setState({ productList: productList });
    }

    handleChangeProductCostPrice = (record, value) => {
        let productList = R.clone(this.state.productList);
        R.map((row) => {
            if (row.id === record.id) {
                row.costPrice = value;
            }
        }, productList)
        this.setState({ productList: productList });
    }

    handleChangeProductWeight = (record, value) => {
        let productList = R.clone(this.state.productList);
        R.map((row) => {
            if (row.id === record.id) {
                row.netWeight = value;
            }
        }, productList)
        this.setState({ productList: productList });
    }

    handleChangeGrossWeight = (record, value) => {
        let productList = R.clone(this.state.productList);
        R.map((row) => {
            if (row.id === record.id) {
                row.grossWeight = value;
            }
        }, productList)
        this.setState({ productList: productList });
    }


    handleChangeProductSize = (record, e) => {
        let productList = R.clone(this.state.productList);
        R.map((row) => {
            if (row.id === record.id) {
                row.size = e.target.value;
            }
        }, productList)
        this.setState({ productList: productList });
    }

    handleDeleteProduct = (record) => {
        let productList = R.difference(this.state.productList, [record])
        this.setState({ productList: productList, retrodictFlag: true });
    }

    handleOpenAddProduct = () => {
        this.props.dispatch({
            type: 'orderProduct/queryProductList',
            payload: {
                page: Constants.DEFAULTPAGE
            }
        });
        this.formRef.handleOpen();
    }


    handleAddProducts = (tempProductList) => {
        this.setState({ productList: R.concat(this.state.productList, tempProductList), retrodictFlag: true });
    }


    handleInitColumns = () => {
        return R.without([null], [
            { title: '品名', dataIndex: 'name', key: 'name' },
            { title: '型号', dataIndex: 'model', key: 'model' },
            { title: '品牌类型', dataIndex: 'branchtypename', key: 'branchtypename' },
            { title: '品牌', dataIndex: 'branch', key: 'branch' },
            {
                title: '数量', dataIndex: 'number', key: 'number',
                render: (text, record, index) => {
                    return (
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.number} onChange={this.handleChangeProductNumber.bind(this, record)} />
                    )
                }
            },
            { title: '单位', dataIndex: 'unit', key: 'unit' },
            {
                title: '包装件数', dataIndex: 'packageNumber', key: 'packageNumber',
                render: (text, record, index) => {
                    return (
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.packageNumber} onChange={this.handleChangePackageNumber.bind(this, record)} />
                    )
                }
            },
            {
                title: '成本单价(CNY)', dataIndex: 'costPrice', key: 'costPrice',
                render: (text, record, index) => {
                    return (
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.costPrice} onChange={this.handleChangeProductCostPrice.bind(this, record)} />
                    )
                }
            },
            {
                title: '销售价', dataIndex: 'price', key: 'price',
                render: (text, record, index) => {
                    return (
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.price} onChange={this.handleChangeProductPrice.bind(this, record)} />
                    )
                }
            },
            { title: '销售价币种', dataIndex: 'currency', key: 'currency' },
            { title: '单净重(Kg)', dataIndex: 'singleWeight', key: 'singleWeight' },
            {
                title: '净重(Kg)', dataIndex: 'netWeight', key: 'netWeight',
                render: (text, record, index) => {
                    return (
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.netWeight} onChange={this.handleChangeProductWeight.bind(this, record)} />
                    )
                }
            },
            {
                title: '毛重(Kg)', dataIndex: 'grossWeight', key: 'grossWeight',
                render: (text, record, index) => {
                    return (
                        <InputNumber disabled={this.props.disabled} min={0} max={99999999999999} value={record.grossWeight} onChange={this.handleChangeGrossWeight.bind(this, record)} />
                    )
                }
            },
            {
                title: '供应商', dataIndex: 'providerName', key: 'providerName'
            },
            { title: '货值', dataIndex: 'totalPrice', key: 'totalPrice' },
            {
                title: '规格', dataIndex: 'size', key: 'size',
                render: (text, record, index) => {
                    return (
                        <Input maxLength="1000" style={{ width: 'auto' }} value={R.isNil(record.size) ? "" : record.size} disabled={record.iseffecthscode === "1" || this.props.disabled} onChange={this.handleChangeProductSize.bind(this, record)} />
                    )
                }
            },
            { title: '申报参数', dataIndex: 'declareElements', key: 'declareElements' },
            { title: '退税率', dataIndex: 'taxrate', key: 'taxrate' },
            { title: '增值税率', dataIndex: 'zzrate', key: 'zzrate' },
            {
                title: '操作', key: 'operation',
                render: (text, record, index) => {
                    return (
                        <div><a href="#" disabled={this.props.disabled} onClick={this.handleDeleteProduct.bind(this, record)}>删除</a></div>
                    );
                }
            }]);
    }

    render() {
        let columns = this.handleInitColumns();
        const { getFieldDecorator } = this.props.form;
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
        let formItemLayout = {
            labelCol: { xs: { span: 24 }, sm: { span: 6 } },
            wrapperCol: { xs: { span: 24 }, sm: { span: 14 } }
        };
        let currency = "";
        let [totalnum, totalweight, totalgross, totleamount, totalpacknum] = [0, 0, 0, 0, 0];
        R.map((product) => {
            currency = product.currency;
            totalnum = totalnum + (R.isNil(product.number) ? 0 : product.number) //总数量
            totalweight = totalweight + (R.isNil(product.netWeight) ? 0 : product.netWeight) //总净重
            totalgross = totalgross + (R.isNil(product.grossWeight) ? 0 : product.grossWeight) //总毛重
            totleamount = totleamount + (R.isNil(product.totalPrice) ? 0 : product.totalPrice) //总货值
            totalpacknum = totalpacknum + (R.isNil(product.packageNumber) ? 0 : product.packageNumber) //总包装件数
        }, this.state.productList);
        totalnum = Math.round(totalnum * 10000) / 10000;
        totalweight = Math.round(totalweight * 10000) / 10000;
        totalgross = Math.round(totalgross * 10000) / 10000;
        totleamount = Math.round(totleamount * 100) / 100;//两位小数 总价只保留两位小数
        totalpacknum = Math.round(totalpacknum * 10000) / 10000;
        this.form.totalnum = totalnum;
        this.form.totalweight = totalweight;
        this.form.totalgross = totalgross;
        this.form.totleamount = totleamount;
        this.form.totalpacknum = totalpacknum;

        //只有自营的按美金收取代理费支持倒推模式
        let disabledDrawerTypes = [];
        let customer = R.isNil(this.props.customer) ? {} : this.props.customer;
        let declarationstyle = this.props.declarationstyle ? this.props.declarationstyle : undefined;
        if (declarationstyle === "2" || customer.feemethod === "2" || customer.csttype === "2" || customer.businessType === "2") disabledDrawerTypes[0] = "2";
        return (
            <div>
                <Form>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="包装方式" hasFeedback>
                                {getFieldDecorator('packtype', {
                                    rules: [{
                                        required: true, message: '请选择包装方式'
                                    }],
                                    initialValue: dataSource.packtype
                                })(
                                    <BizParams disabled={this.props.disabled} sprCode='packtype' />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="最大包装件数" hasFeedback>
                                {getFieldDecorator('maxpacknum', {
                                    rules: [{
                                        required: true, message: '请输入最大包装件数',
                                    }],
                                    initialValue: dataSource.maxpacknum
                                })(
                                    <InputNumber disabled={this.props.disabled} min={1} max={99999999999999} precision={0} style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="包装种类" hasFeedback>
                                {getFieldDecorator('kindpackage', {
                                    rules: [{
                                        required: true, message: '请选择包装种类'
                                    }],
                                    initialValue: dataSource.kindpackage ? dataSource.kindpackage.split('|') : []
                                })(
                                    <BizParams disabled={this.props.disabled} sprCode="kindpackage" mode="multiple" onChange={this.handleChangeKindPackage.bind(this)} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12} style={{ display: this.state.packtypeelse ? "inline-block" : "none" }}>
                            <FormItem {...formItemLayout} label="实际种类" hasFeedback>
                                {getFieldDecorator('packtypeelse', {
                                    rules: [{
                                        required: this.state.packtypeelse, message: '请输入实际种类'
                                    }],
                                    initialValue: dataSource.packtypeelse
                                })(
                                    <Input disabled={this.props.disabled} maxLength="20" />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem>
                                <Button type="primary" size={'default'} disabled={this.props.disabled} onClick={this.handleOpenAddProduct.bind(this)}>添加产品</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <Table rowKey={record => record.id} dataSource={this.state.productList} columns={columns} size={'middle'} style={{ marginTop: 0 }} scroll={{ x: true }} pagination={false} />
                <div style={{ textAlign: 'center', marginTop: 20 }}><span>总数量: </span>{R.isNil(totalnum) ? 0 : totalnum}&nbsp;&nbsp;&nbsp;&nbsp;
                <span>总净重: </span><span>{R.isNil(totalweight) ? 0 : totalweight}&nbsp;kg&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span>总毛重: </span><span>{R.isNil(totalgross) ? 0 : totalgross}&nbsp;kg&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span>总货值: </span><span>{R.isNil(totleamount) ? 0 : totleamount}&nbsp;{currency}&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span>总包装件数: </span><span>{R.isNil(totalpacknum) ? 0 : totalpacknum}</span></div>
                <ChooseProduct wrappedComponentRef={(inst) => this.formRef = inst} handleAddProducts={this.handleAddProducts} dispatch={this.props.dispatch} orderId={dataSource.id} customer={customer}/>
            </div>
        )
    }
})